<template>
  <div class="store-page">
    <div class="search-field">
      <el-form :model="searchForm" inline>
        <el-form-item label="门店名称" prop="name">
          <el-input
            placeholder="请输入门店名称"
            v-model="searchForm.name"
            autocomplete="off"
          />
        </el-form-item>

        <el-form-item label="门店分类" prop="storeCategoryId">
          <el-select
            style="width: 220px"
            v-model="searchForm.storeCategoryId"
            placeholder="选择门店类型"
          >
            <el-option
              v-for="option in storeCategoryList"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="门店区域" prop="storeGroupId">
          <el-select
            style="width: 220px"
            v-model="searchForm.storeGroupId"
            placeholder="选择门店区域"
          >
            <el-option
              v-for="option in storeGroupList"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否营业" prop="isClosed">
          <el-select
            style="width: 200px"
            v-model="searchForm.isClosed"
            placeholder="是否营业"
          >
            <el-option
              v-for="option in closeList"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="enabled">
          <el-select
            style="width: 200px"
            v-model="searchForm.enabled"
            placeholder="选择状态"
          >
            <el-option
              v-for="option in statusOptions"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="省市区" prop="provinceId">
          <el-select
            style="width: 120px"
            v-model="searchForm.provinceId"
            placeholder="选择省"
            @change="changeProvince"
          >
            <el-option
              v-for="option in regionData"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          <el-select
            style="width: 120px"
            v-model="searchForm.cityId"
            placeholder="选择市"
            @change="changeCity"
          >
            <el-option
              v-for="option in cityList"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          <el-select
            style="width: 120px"
            v-model="searchForm.areaId"
            placeholder="选择县/区"
            @change="changeArea"
          >
            <el-option
              v-for="option in areaList"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>
            <el-button type="primary" @click="startSearch"> 查询 </el-button>
            <el-button @click="startClear"> 重置 </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-pagination-content">
      <div class="btns-fun-field">
        <!-- v-if="userPermission.addUserPerm" -->
        <el-button
          type="primary"
          @click.prevent="showAddEditDialog"
          :icon="Plus"
        >
          新增门店
        </el-button>
        <el-button
          type="primary"
          @click.prevent="showBatchLoadDialog"
          :icon="Plus"
        >
          批量导入门店
        </el-button>
      </div>
      <div class="table-field">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          v-loading="tableLoading"
        >
          <el-table-column prop="number" label="编号" width="80" />
          <!-- <el-table-column prop="shortName" label="短名称" width="120" /> -->
          <el-table-column prop="name" label="门店名称" width="190" />
          <el-table-column prop="storeGroupName" label="门店区域" width="120" />
          <el-table-column
            prop="storeCategoryName"
            label="门店分类"
            width="100"
          />
          <el-table-column prop="isClosed" label="是否营业" width="90">
            <template #default="scopedd">
              <el-tag v-if="scopedd.row.isClosed == 2" type="danger">
                未营业
              </el-tag>
              <el-tag v-else type="success">营业</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="enabled" label="状态" width="80">
            <template #default="scopedd">
              <el-tag v-if="scopedd.row.enabled == 2" type="danger">
                禁用
              </el-tag>
              <el-tag v-else type="success">启用</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="outStoreNumber"
            label="外门店编号"
            width="100"
          />
          <el-table-column prop="provinceName" label="省" width="80" />
          <el-table-column prop="cityName" label="市" width="80" />
          <el-table-column prop="areaName" label="区/县" width="80" />
          <el-table-column prop="address" label="详细地址" width="190">
            <template #default="scoped">
              <div class="table-inner-content">
                <el-tooltip :content="scoped.row.address" placement="top">
                  <template #content>
                    <div style="width: 500px">{{ scoped.row.address }}</div>
                  </template>
                  <div>{{ scoped.row.address }}</div></el-tooltip
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" min-width="220px" fixed="right">
            <template #default="scoped">
              <!-- v-if="rolePermission.editRolePerm" -->
              <el-button
                type="success"
                size="small"
                @click.prevent="showAddEditDialog(scoped.row, 2)"
                >编辑</el-button
              >
              <!-- v-if="rolePermission.removeRolePerm" -->
              <el-button
                type="danger"
                size="small"
                @click.prevent="showRemoveDialog(scoped.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-field">
        <el-pagination
          v-model:current-page="formData.pageIndex"
          v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <StoreAdd v-model="addUpdateRef"></StoreAdd>
    <StoreRemove v-model="removeRef"></StoreRemove>
    <StoreBatchLoad v-model="batchLoadRef"></StoreBatchLoad>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { getStorePagination, getStoreAllList } from '@/api/tms-store.api'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
// import { useUserPermission } from "@/utils/permission.utils";
import StoreRemove from './component/StoreRemove.vue'
import StoreAdd from './component/StoreAdd.vue'
import StoreBatchLoad from './component/StoreBatchLoad.vue'
import { getCanUseCode } from '@/api/fms-code-dict.api'
import { getStoreCategoryAllList } from '@/api/tms-store-category.api'
import { getStoreGroupAllList } from '@/api/tms-store-group.api'
import { regionData } from 'element-china-area-data'
import { statusOptions } from '@/utils/common.utils'
import { getUserAllList } from '@/api/ums-user.api'

// const userPermission = useUserPermission();

/****
 * =============== 新增、修改相关操作 =====================
 */
const closeList = ref([
  {
    id: 0,
    name: '营业',
  },
  {
    id: 1,
    name: '未营业',
  },
])

const addUpdateRef = reactive({
  visible: false,
  disabled: false,
  title: `门店`,
  curSelectRow: {},
  storeCategoryList: [],
  storeGroupList: [],
  userList: [],
  closeList: closeList.value,
  form: {},
  rules: {},
  refreshDataList: () => {
    getDataList()
  },
})

const requestCanUseCode = () => {
  getCanUseCode({ type: 8 })
    .then((res: any) => {
      console.log('getCanUseCode: ', res)
      addUpdateRef.form.number = res
    })
    .catch((err) => {
      ElMessage.error(err.msg)
    })
}

const showAddEditDialog = (item: any, type: number) => {
  //新增 门店
  if (item.target) {
    let form = {
      id: null,
      name: '',
      number: '',
      storeGroupId: '',
      storeGroupName: '',
      storeCategoryId: '',
      storeCategoryName: '',
      enabled: '',
      isClosed: '',
      shortName: '',
      mark: '',
      outStoreNumber: '',
      provinceId: '',
      provinceName: '',
      cityId: '',
      cityName: '',
      areaId: '',
      areaName: '',
      address: '',
      userId: '',
      provincecityarea: [],
    }
    addUpdateRef.visible = true
    addUpdateRef.disabled = false
    addUpdateRef.form = form
    requestCanUseCode()
    return
  }

  let form = {
    id: item.id,
    name: item.name,
    number: item.number,
    storeGroupId: item.storeGroupId,
    storeGroupName: item.storeGroupName,
    storeCategoryId: item.storeCategoryId,
    storeCategoryName: item.storeCategoryName,
    enabled: item.enabled + '',
    isClosed: item.isClosed,
    shortName: item.shortName,
    mark: item.mark,
    outStoreNumber: item.outStoreNumber,
    provinceId: item.provinceId,
    provinceName: item.provinceName,
    cityId: item.cityId,
    cityName: item.cityName,
    areaId: item.areaId,
    areaName: item.areaName,
    address: item.address,
    userId: item.userId,
    provincecityarea: [
      '' + item.provinceId,
      '' + item.cityId,
      '' + item.areaId,
    ],
  }

  console.log('provincecityarea: ', form.provincecityarea)
  addUpdateRef.visible = true
  addUpdateRef.disabled = true
  addUpdateRef.form = form
}

//批量加入
const batchLoadRef = reactive({
  visible: false,
  title: `批量导入门店`,
  form: {},
  refreshDataList: () => {
    getDataList()
    requestStoreGroupAllList()
  },
})
const showBatchLoadDialog = () => {
  let form = {}
  batchLoadRef.visible = true
  batchLoadRef.form = form
}
/****
 * =============== 删除操作 =====================
 */
const removeRef = reactive({
  visible: false,
  title: '门店',
  curSelectRow: {},
  refreshDataList: () => {
    getDataList()
  },
})
const showRemoveDialog = (item: any) => {
  removeRef.visible = true
  removeRef.curSelectRow = item
}

/****
 * =============== 搜索、表格、分页 =====================
 */
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

const searchForm = ref({
  name: '',
  number: '',
  storeGroupId: '',
  storeGroupName: '',
  storeCategoryId: '',
  storeCategoryName: '',
  enabled: '',
  isClosed: '',
  shortName: '',
  mark: '',
  outStoreNumber: '',
  provinceId: '',
  provinceName: '',
  cityId: '',
  cityName: '',
  areaId: '',
  areaName: '',
  address: '',
})

const cityList = ref([])
const areaList = ref([])
const changeProvince = (value) => {
  let provinceId = value
  let provinceItem = regionData.find((item) => {
    return item.value == provinceId
  })
  if (provinceItem) {
    cityList.value = provinceItem.children || []
  } else {
    cityList.value = []
  }
  areaList.value = []
  searchForm.value.cityId = ''
  searchForm.value.areaId = ''
}
const changeCity = (value) => {
  let cityId = value
  let cityItem = cityList.value.find((item) => {
    return item.value == cityId
  })
  if (cityItem) {
    areaList.value = cityItem.children || []
  } else {
    areaList.value = []
  }
  searchForm.value.areaId = ''
}

const changeArea = (value) => {}

const tableLoading = ref(false)
const tableData = ref([])
/***
 * 开始搜索
 */
const startSearch = () => {
  formData.pageIndex = 1
  getDataList()
}

/***
 * 重置搜索条件
 */
const startClear = () => {
  formData.pageIndex = 1
  let value = searchForm.value
  Object.keys(value).forEach((key) => {
    ;(value as any)[key] = ''
  })
  getDataList()
}

const handleSizeChange = (value: number) => {
  formData.pageSize = value
  getDataList()
}

const handleCurrentChange = (value: number) => {
  formData.pageIndex = value
  getDataList()
}

const getDataList = () => {
  let searchCondition: any = {}

  let name = searchForm.value.name
  if (name) {
    searchCondition.name = name
  }
  let number = searchForm.value.number
  if (number) {
    searchCondition.number = number
  }
  let storeGroupId = searchForm.value.storeGroupId
  if (storeGroupId) {
    searchCondition.storeGroupId = storeGroupId
  }
  let storeGroupName = searchForm.value.storeGroupName
  if (storeGroupName) {
    searchCondition.storeGroupName = storeGroupName
  }
  let storeCategoryId = searchForm.value.storeCategoryId
  if (storeCategoryId) {
    searchCondition.storeCategoryId = storeCategoryId
  }
  let storeCategoryName = searchForm.value.storeCategoryName
  if (storeCategoryName) {
    searchCondition.storeCategoryName = storeCategoryName
  }
  let enabled = searchForm.value.enabled
  if (enabled) {
    searchCondition.enabled = enabled
  }
  let isClosed = searchForm.value.isClosed
  if (isClosed !== null && isClosed !== '') {
    searchCondition.isClosed = isClosed
  }
  let shortName = searchForm.value.shortName
  if (shortName) {
    searchCondition.shortName = shortName
  }
  let mark = searchForm.value.mark
  if (mark) {
    searchCondition.mark = mark
  }
  let outStoreNumber = searchForm.value.outStoreNumber
  if (outStoreNumber) {
    searchCondition.outStoreNumber = outStoreNumber
  }
  let provinceId = searchForm.value.provinceId
  if (provinceId) {
    searchCondition.provinceId = provinceId
  }
  let provinceName = searchForm.value.provinceName
  if (provinceName) {
    searchCondition.provinceName = provinceName
  }
  let cityId = searchForm.value.cityId
  if (cityId) {
    searchCondition.cityId = cityId
  }
  let cityName = searchForm.value.cityName
  if (cityName) {
    searchCondition.cityName = cityName
  }
  let areaId = searchForm.value.areaId
  if (areaId) {
    searchCondition.areaId = areaId
  }
  let areaName = searchForm.value.areaName
  if (areaName) {
    searchCondition.areaName = areaName
  }
  let address = searchForm.value.address
  if (address) {
    searchCondition.address = address
  }
  tableLoading.value = true
  getStorePagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
    ...searchCondition,
  })
    .then(function (res: any) {
      tableLoading.value = false
      console.log(res)
      tableData.value = res.list || []
      formData.total = Number(res.total)
    })
    .catch((error) => {
      console.log(error)
      tableLoading.value = false
    })
}

const storeCategoryList = ref([])
const requestStoreCategoryAllList = () => {
  getStoreCategoryAllList({})
    .then((res: any) => {
      storeCategoryList.value = res || []
      addUpdateRef.storeCategoryList = storeCategoryList.value
      console.log('storeCategoryList.value: ', storeCategoryList.value)
    })
    .catch((err) => {
      console.log(err)
    })
}

const storeGroupList = ref([])
const requestStoreGroupAllList = () => {
  getStoreGroupAllList({})
    .then((res) => {
      storeGroupList.value = res || []
      addUpdateRef.storeGroupList = storeGroupList.value
    })
    .catch((err) => {
      console.log(err)
    })
}

const userList = ref([])
const requesttUserAllList = () => {
  getUserAllList()
    .then((res) => {
      userList.value = res || []
      addUpdateRef.userList = res || []
      console.log('getUserAllList: ', res)
    })
    .catch((err) => {
      console.log(err)
    })
}

onMounted(() => {
  requesttUserAllList()
  requestStoreCategoryAllList()
  requestStoreGroupAllList()
  getDataList()
})
</script>
<style lang="scss" scopedd>
.store-page {
  height: 100%;
}

.btns-fun-field {
  margin-bottom: 20px;
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.btn-inner {
  display: flex;
  justify-content: center;
  color: #fff;
}

.tag-field {
  .el-tag {
    margin-right: 5px;
    &:last-child {
      margin-right: 0;
    }
  }
}

.search-field {
  margin-bottom: 12px;
  background: #fff;
  padding: 20px 20px 0px 20px;
  border-radius: 8px;
}

.store-page-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}
</style>
